package com.lvmama.rhino.collector.action

import com.lvmama.rhino.collector.JsonUtil
import com.lvmama.rhino.collector.utils.GZipUtils
import com.lvmama.rhino.collector.vo.{AIMachineReceipt, ClientLog, PushMessageReceipt}
import org.apache.commons.codec.binary.Base64
import org.apache.log4j.Logger
import org.springframework.http.{HttpStatus, ResponseEntity}
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.{RequestMapping, RequestMethod, RequestParam, ResponseBody}

/**
  * Created by yuanxiaofeng on 2016/3/14.
  */
@RequestMapping(Array("/log"))
@Controller
class LogCollectAction {
  private val clientSide = Logger.getLogger("client_side")
  private val messageReceipt = Logger.getLogger("message_receipt")
  private val AIReceipt = Logger.getLogger("ai_receipt")

  @RequestMapping(value = Array("/app"),params = Array("data"), method = Array(RequestMethod.POST))
  @ResponseBody
  def trackAppLog(@RequestParam("data")  data: String): ResponseEntity[Void] ={
    try {
      this.batchOutputLog[ClientLog](clientSide, data)
    } catch {
      case e:Exception => println(s"rhino-collector parse error,param can not uncompress or transform to ClientLog $data")
    }
    ResponseEntity.status(HttpStatus.OK).build()
  }

  @RequestMapping(value = Array("/app"),params = Array("push"), method = Array(RequestMethod.POST))
  @ResponseBody
  def pushMessage(@RequestParam("push")  push: String): ResponseEntity[Void] ={
    try {
      this.realTimeOutputLog[PushMessageReceipt](messageReceipt, push)
    } catch {
      case e:Exception => println(s"rhino-collector parse error,param can not uncompress or transform to PushMessageReceipt $push")
    }
    ResponseEntity.status(HttpStatus.OK).build()
  }

  @RequestMapping(value = Array("/app"), params = Array("ai"), method = Array(RequestMethod.POST))
  @ResponseBody
  def AIMessage(@RequestParam("ai") ai: String): ResponseEntity[Void] = {
    try {
      this.realTimeOutputLog[AIMachineReceipt](AIReceipt, ai)
    } catch {
      case e: Exception => println(s"rhino-collector parse error,param can not uncompress or transform to AIMachineReceipt $ai")
    }
    ResponseEntity.status(HttpStatus.OK).build()
  }

  @throws(classOf[Exception])
  def batchOutputLog[T](logger: Logger, data: String)(implicit m: Manifest[T]): Unit ={
    val str = GZipUtils.unCompress(data)
    val logModel = JsonUtil.fromJson[T](str)
    logger.info(logModel.toString)
  }

  def realTimeOutputLog[T](logger: Logger, push: String)(implicit m: Manifest[T]): Unit ={
    val message = new String(Base64.decodeBase64(push), "UTF-8").replace("\\n", "")
    val logModel = JsonUtil.fromJson[T](message)
    logger.info(logModel.toString)
  }
}

